package com.foton.websocket.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.foton.websocket.controller.Ticket;
import org.apache.commons.codec.binary.Hex;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;



public class WeixinHelper {

    // 企业id
    public static final String APP_ID = "ww9eba8b280a624bab";
    // CRM电脑端
    public static final String CRM_PC_AGENT_ID = "1000004";
    public static final String CRM_PC_CORPSECRET = "P88DAlsmLRIdBWWQL71jYof_obEKS9_TYx5AHIJKZsU";

    /**
     * 存放ticket的容器
     */
    private static Map<String, Ticket> ticketMap = new HashMap<>();

    /**
     * 获取token
     * @return
     */
    public static String getAccessToken(String secret) {
        //获取token
        String getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + WeixinHelper.APP_ID + "&corpsecret=" + secret;
        String tokenContent = HttpService.get(getTokenUrl);
        System.out.println("tokenContent = " + tokenContent);
        JSONObject jsonObject = JSONObject.parseObject(tokenContent);
        String accessToken = jsonObject.getString("access_token");
        System.out.println("accessToken = " + accessToken);
        return accessToken;
    }

    /**
     * 获取jsapi_ticket
     * @param secret
     * @param type
     * @return
     */
    public static String getJsApiTicket(String secret, String type) {
        String accessToken = getAccessToken(secret);
        String key = accessToken;
        if (!StringUtils.isEmpty(accessToken)) {
            if ("agent_config".equals(type)){
                key = type + "_" + accessToken;
            }
            Ticket ticket = ticketMap.get(key);
            if (!ObjectUtils.isEmpty(ticket)) {
                long now = Calendar.getInstance().getTime().getTime();
                Long expiresIn = ticket.getExpiresIn();
                //有效期内的ticket 直接返回
                if (expiresIn - now > 0) {
                    return ticket.getTicket();
                }
            }
            ticket = getJsApiTicketFromWeChatPlatform(accessToken, type);
            if (ticket != null) {
                ticketMap.put(key, ticket);
                return ticket.getTicket();
            }
        }
        return null;
    }


    /**
     * 获取企业的jsapi_ticket或应用的jsapi_ticket
     * @param accessToken
     * @param type 为agent_config时获取应用的jsapi_ticket，否则获取企业的jsapi_ticket
     * @return
     */
    public static Ticket getJsApiTicketFromWeChatPlatform(String accessToken, String type) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" + accessToken+ "&type=" + type;

//            url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + accessToken;

        Long now = System.currentTimeMillis();
        if (!StringUtils.isEmpty(accessToken)) {
            String body = HttpService.get(url);
            System.out.println("ticketContent = " + body);
            if (!StringUtils.isEmpty(body)) {
                JSONObject object = JSON.parseObject(body);
                if (object.getIntValue("errcode") == 0) {
                    Ticket ticket = new Ticket();
                    ticket.setTicket(object.getString("ticket"));
                    ticket.setExpiresIn(now + object.getLongValue("expires_in") * 1000);
                    return ticket;
                }
            }
        }
        return null;
    }


    /**
     * 获取JS-SDK使用权限签名
     * @param ticket
     * @param nonceStr
     * @param timestamp
     * @param url
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getJSSDKSignature(String ticket, String nonceStr, long timestamp, String url) throws NoSuchAlgorithmException {
        String unEncryptStr = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        MessageDigest sha = MessageDigest.getInstance("SHA");
        // 调用digest方法，进行加密操作
        byte[] cipherBytes = sha.digest(unEncryptStr.getBytes());

//        将字节数组转换为十六进制字符串
        String encryptStr = Hex.encodeHexString(cipherBytes);
        return encryptStr;
    }

}
